package shuaige.jdk.多线程.concurrent.completableFuture;

import lombok.SneakyThrows;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class 结果处理_异步计算后_处理上一阶段的执行结果 {

    private static ExecutorService executor1 = Executors.newSingleThreadExecutor();
    private static ExecutorService executor2 = Executors.newSingleThreadExecutor();

    @SneakyThrows
    public static void main(String[] args) {
        获取结果后再传给下一个_不传值无返回值();
    }

    public static void 获取结果后再传给下一个_不传值无返回值() throws ExecutionException, InterruptedException {
        CompletableFuture<String> completableFuture
                = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello";
        });
        // 当这个阶段正常完成时，执行给定的操作
        CompletableFuture<Void> future = completableFuture
                .thenRun(() -> System.out.println("Computation finished."));
        // 无返回值
        Void unused = future.get();
        System.out.println(unused);
    }

    public static void 获取结果后再传给下一个_继续传值无返回值() throws ExecutionException, InterruptedException {
        CompletableFuture<String> completableFuture
                = CompletableFuture.supplyAsync(() -> "Hello");
        // 当此阶段正常完成时，将使用此阶段的结果作为提供的操作的参数来执行
        CompletableFuture<Void> future = completableFuture
                .thenAccept(s -> System.out.println("Computation returned: " + s));
        // 无返回值
        Void unused = future.get();
        System.out.println(unused);
    }

    public static void 获取结果后再传给下一个_继续传值有返回值() throws ExecutionException, InterruptedException {
        CompletableFuture<String> completableFuture
                = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello";
        });
        // 当此阶段正常完成时，将使用此阶段的结果作为所提供函数的参数来执行
        CompletableFuture<String> future = completableFuture.thenApply(s -> s + " World");
        // 有返回值
        String s = future.get();
        System.out.println(s);
    }

}
